<template>
  <div class="conversation-sidebar" :class="{ 'collapsed': isCollapsed }">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="header-content">
        <h2 class="header-title" v-if="!isCollapsed">对话列表</h2>
        <button 
          class="collapse-btn"
          @click="toggleCollapse"
          :aria-label="isCollapsed ? '展开侧边栏' : '收起侧边栏'"
        >
          <menu-icon v-if="isCollapsed" />
          <menu-fold-icon v-else />
        </button>
      </div>
      <button 
        v-if="!isCollapsed"
        class="new-chat-btn"
        @click="createNewChat"
        aria-label="新建对话"
      >
        <add-icon size="18" />
        <span>新建对话</span>
      </button>
    </div>

    <!-- 对话列表 -->
    <div class="sidebar-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span v-if="!isCollapsed" class="loading-text">加载中...</span>
      </div>

      <!-- 对话列表 -->
      <div v-else-if="conversations.length > 0" class="conversations-list">
        <transition-group name="conversation" tag="div">
          <div
            v-for="(conv, index) in conversations"
            :key="conv.id"
            class="conversation-item"
            :class="{ 
              'active': activeConversationId === conv.id,
              'collapsed': isCollapsed 
            }"
            @click="selectConversation(conv)"
            :style="{ '--delay': `${index * 0.05}s` }"
          >
            <div class="conversation-avatar">
              <div class="avatar-placeholder">
                {{ conv.roleName ? conv.roleName.charAt(0) : 'AI' }}
              </div>
              <div class="status-dot" :class="{ 'active': conv.isActive() }"></div>
            </div>
            
            <div v-if="!isCollapsed" class="conversation-info">
              <div class="conversation-title">
                {{ conv.title || conv.roleName || '未命名对话' }}
              </div>
              <div class="conversation-meta">
                <span class="role-name">{{ conv.roleName }}</span>
                <span class="last-time" v-if="conv.lastMessageTime">
                  {{ formatTime(conv.lastMessageTime) }}
                </span>
              </div>
            </div>

            <div v-if="!isCollapsed" class="conversation-actions">
              <button 
                class="action-btn delete-btn"
                @click.stop="deleteConversation(conv.id)"
                aria-label="删除对话"
              >
                <delete-icon size="14" />
              </button>
            </div>
          </div>
        </transition-group>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">💬</div>
        <div v-if="!isCollapsed" class="empty-text">
          <p>暂无对话记录</p>
          <p>开始一个新对话吧</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  MenuIcon, 
  MenuFoldIcon, 
  AddIcon, 
  DeleteIcon 
} from 'tdesign-icons-vue-next';
import apiClient from '@/utils/api';

// 定义接口类型
interface ConversationItem {
  id: string;
  userId?: string;
  roleId?: string;
  roleName?: string;
  title?: string;
  status?: number;
  lastMessageTime?: string;
  isEnabled?: number;
  isActive(): boolean;
}

// Props
const props = defineProps<{
  activeConversationId?: string;
}>();

// Emits
const emit = defineEmits<{
  conversationSelected: [conversation: ConversationItem];
  newChatRequested: [];
}>();

const router = useRouter();
const route = useRoute();

// 响应式数据
const conversations = ref<ConversationItem[]>([]);
const loading = ref(false);
const isCollapsed = ref(false);

// 计算属性
const activeConversationId = computed(() => {
  return props.activeConversationId || route.params.id as string;
});

// 方法
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
  // 保存折叠状态到本地存储
  localStorage.setItem('sidebar-collapsed', String(isCollapsed.value));
};

const loadConversations = async () => {
  loading.value = true;
  try {
    const response = await apiClient.get('/ai/conversation/list', {
      params: {
        // 可以添加分页和排序参数
        page: 1,
        size: 50,
        orderBy: 'lastMessageTime',
        orderDirection: 'desc'
      }
    });

    if (response.data?.success && Array.isArray(response.data.result)) {
      conversations.value = response.data.result.map((conv: any) => ({
        ...conv,
        isActive: () => conv.status === 1
      }));
    } else {
      // 如果后端返回失败或数据格式不正确，使用空数组
      conversations.value = [];
    }
  } catch (error) {
    console.error('获取对话列表失败:', error);
    // 可以显示错误提示
    conversations.value = [];
  } finally {
    loading.value = false;
  }
};

const selectConversation = (conversation: ConversationItem) => {
  // 发出事件通知父组件
  emit('conversationSelected', conversation);
  
  // 跳转到聊天页面，确保路由参数正确更新
  if (route.name !== 'Chat' || route.params.id !== conversation.id) {
    router.push({
      name: 'Chat',
      params: { id: conversation.id }
    }).then(() => {
      console.log('成功跳转到对话:', conversation.id);
    }).catch((error) => {
      console.error('跳转失败:', error);
    });
  }
};

const createNewChat = () => {
  emit('newChatRequested');
  router.push('/home');
};

const deleteConversation = async (conversationId: string) => {
  if (!confirm('确定要删除这个对话吗？')) {
    return;
  }

  try {
    const response = await apiClient.delete(`/ai/conversation/${conversationId}`);
    if (response.data?.success) {
      // 从列表中移除已删除的对话
      conversations.value = conversations.value.filter(c => c.id !== conversationId);
      
      // 如果删除的是当前对话，跳转到首页
      if (conversationId === activeConversationId.value) {
        router.push('/home');
      }
    }
  } catch (error) {
    console.error('删除对话失败:', error);
    alert('删除对话失败，请重试');
  }
};

const formatTime = (timeStr?: string): string => {
  if (!timeStr) return '';
  
  const time = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - time.getTime();
  
  // 一天内显示时间
  if (diff < 24 * 60 * 60 * 1000) {
    return time.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }
  
  // 一周内显示星期
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[time.getDay()];
  }
  
  // 更久显示日期
  return time.toLocaleDateString('zh-CN', { 
    month: 'short', 
    day: 'numeric' 
  });
};

// 生命周期
onMounted(() => {
  // 恢复折叠状态
  const collapsed = localStorage.getItem('sidebar-collapsed');
  if (collapsed === 'true') {
    isCollapsed.value = true;
  }
  
  // 加载对话列表
  loadConversations();
});

// 暴露方法供父组件调用
defineExpose({
  loadConversations,
  conversations
});
</script>

<style scoped>
.conversation-sidebar {
  width: 320px;
  height: 100vh;
  background: rgba(20, 20, 20, 0.95);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(124,77,255,0.2);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  position: relative;
  z-index: 100;
}

.conversation-sidebar.collapsed {
  width: 80px;
}

/* 侧边栏头部 */
.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid rgba(124,77,255,0.15);
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  color: #fff;
  background: linear-gradient(90deg, #c7b8ff, #7c4dff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.collapse-btn {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: rgba(124,77,255,0.1);
  border: 1px solid rgba(124,77,255,0.2);
  color: #7c4dff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background: rgba(124,77,255,0.2);
  transform: scale(1.05);
}

.new-chat-btn {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #7c4dff, #6a3cff);
  border: none;
  border-radius: 12px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.new-chat-btn:hover {
  background: linear-gradient(135deg, #6a3cff, #5a2cef);
  transform: translateY(-1px);
  box-shadow: 0 8px 25px rgba(124,77,255,0.3);
}

/* 侧边栏内容 */
.sidebar-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  gap: 12px;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(124,77,255,0.2);
  border-top-color: #7c4dff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #888;
  font-size: 14px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 对话列表 */
.conversations-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.conversations-list::-webkit-scrollbar {
  width: 4px;
}

.conversations-list::-webkit-scrollbar-track {
  background: rgba(255,255,255,0.05);
}

.conversations-list::-webkit-scrollbar-thumb {
  background: rgba(124,77,255,0.3);
  border-radius: 2px;
}

.conversation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  margin: 0 16px 8px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  animation: conversationSlideIn 0.4s ease-out both;
  animation-delay: var(--delay);
  position: relative;
}

.conversation-item:hover {
  background: rgba(124,77,255,0.1);
  transform: translateX(4px);
}

.conversation-item.active {
  background: rgba(124,77,255,0.2);
  border: 1px solid rgba(124,77,255,0.4);
  box-shadow: 0 4px 15px rgba(124,77,255,0.2);
}

.conversation-item.collapsed {
  margin: 0 16px 12px;
  padding: 12px;
  justify-content: center;
}

.conversation-avatar {
  position: relative;
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(135deg, #7c4dff, #a78bfa);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  text-transform: uppercase;
}

.status-dot {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #666;
  border: 2px solid rgba(20, 20, 20, 0.95);
  transition: all 0.3s ease;
}

.status-dot.active {
  background: #4caf50;
  box-shadow: 0 0 8px rgba(76,175,80,0.6);
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-title {
  font-size: 15px;
  font-weight: 500;
  color: #fff;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.conversation-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #888;
}

.role-name {
  color: #7c4dff;
  font-weight: 500;
}

.last-time {
  color: #666;
}

.conversation-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.conversation-item:hover .conversation-actions {
  opacity: 1;
}

.action-btn {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  background: rgba(255,255,255,0.1);
  border: none;
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: rgba(255,107,107,0.2);
  color: #ff6b6b;
  transform: scale(1.1);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  color: #888;
}

.empty-text p {
  margin: 4px 0;
  font-size: 14px;
}

.empty-text p:first-child {
  font-weight: 500;
  color: #aaa;
}

/* 动画 */
@keyframes conversationSlideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.conversation-enter-active,
.conversation-leave-active {
  transition: all 0.3s ease;
}

.conversation-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.conversation-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .conversation-sidebar {
    width: 280px;
  }
  
  .conversation-sidebar.collapsed {
    width: 60px;
  }
  
  .sidebar-header {
    padding: 16px;
  }
  
  .conversation-item {
    margin: 0 12px 6px;
    padding: 10px 16px;
  }
}
</style>